package com.tuoku.onepass

import android.content.Intent
import android.os.Bundle
import android.view.MotionEvent
import android.view.View
import android.view.inputmethod.EditorInfo
import android.view.inputmethod.InputMethodManager
import android.widget.Button
import android.widget.CheckBox
import android.widget.EditText
import android.widget.ImageButton
import android.widget.LinearLayout
import android.widget.RadioButton
import android.widget.TextView
import android.widget.Toast
import androidx.activity.enableEdgeToEdge
import androidx.appcompat.app.AppCompatActivity
import androidx.appcompat.content.res.AppCompatResources
import androidx.appcompat.widget.TooltipCompat
import androidx.core.view.ViewCompat
import androidx.core.view.WindowInsetsCompat
import androidx.core.widget.addTextChangedListener


class LoginAccountActivity : AppCompatActivity() {

    private lateinit var etAccount: EditText

    private lateinit var etPassword: EditText

    private lateinit var cbRemote: CheckBox

    private lateinit var tvRemote: TextView

    private lateinit var ibRemoteDesc: ImageButton

    private lateinit var tvForgetPwd: TextView

    private lateinit var protocolSection: LinearLayout

    private lateinit var rbAgreeProtocol: RadioButton

    private lateinit var btLogin: Button

    private lateinit var tvOtherLogin: TextView

    private var isPasswordVisible: Boolean = false

    private var loginEnable: Boolean = false

    override fun onCreate(savedInstanceState: Bundle?) {
        super.onCreate(savedInstanceState)
        enableEdgeToEdge()
        setContentView(R.layout.activity_login_account)
        ViewCompat.setOnApplyWindowInsetsListener(findViewById(R.id.main)) { v, insets ->
            val systemBars = insets.getInsets(WindowInsetsCompat.Type.systemBars())
            v.setPadding(systemBars.left, systemBars.top, systemBars.right, systemBars.bottom)
            insets
        }

        initViews()

        setAccountListener()
        setPasswordListener()
        setRemoteListener()
        setRemoteDescListener()
        setAgreeProtocolListener()
        setLoginListener()
        setOtherLoginListener()
    }

    private fun initViews() {
        etAccount = findViewById(R.id.et_account)
        etPassword = findViewById(R.id.et_password)
        cbRemote = findViewById(R.id.cb_remote)
        tvRemote = findViewById(R.id.tv_remote)
        ibRemoteDesc = findViewById(R.id.ib_remote_desc)
        tvForgetPwd = findViewById(R.id.tv_forget_pwd)
        protocolSection = findViewById(R.id.protocol_section)
        rbAgreeProtocol = findViewById(R.id.rb_agree_protocol)
        btLogin = findViewById(R.id.bt_login)
        tvOtherLogin = findViewById(R.id.tv_other_login)

        TooltipCompat.setTooltipText(tvRemote,
            "远程登录是连接到服务器验证账号密码登录\n不开启则在本机验证")
    }

    private fun setAccountListener() {
        etAccount.setOnFocusChangeListener { view, hasFocus ->
            if (!hasFocus) {
                // 失去焦点时校验登录表单
                validLoginForm()
            }
        }
    }

    private fun setPasswordListener() {
        // 设置Touch监听器处理drawable点击
        etPassword.setOnTouchListener { v, event ->
            if (event.action == MotionEvent.ACTION_UP) {
                val drawables = etPassword.compoundDrawables
                val rightDrawable = drawables[2]

                if (rightDrawable != null && event.rawX >=
                    (etPassword.right - rightDrawable.bounds.width())) {
                    togglePasswordVisibility()
                    return@setOnTouchListener true
                }
            }
            return@setOnTouchListener false
        }

        etPassword.addTextChangedListener { editable ->
            editable?.length?.let {
                // 密码文本大于等于6时校验登录表单
                if (it >= 6) {
                    validLoginForm()
                }
            }
        }

        etPassword.setOnFocusChangeListener { view, hasFocus ->
            if (!hasFocus) {
                // 失去焦点时校验登录表单
                validLoginForm()
            }
        }
    }

    private fun togglePasswordVisibility() {
        if (isPasswordVisible) {
            // 隐藏密码
            etPassword.inputType = EditorInfo.TYPE_CLASS_TEXT or
                    EditorInfo.TYPE_TEXT_VARIATION_PASSWORD
            val icHide = AppCompatResources.getDrawable(baseContext, R.drawable.ic_pwd_hide_20dp)
            etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, icHide, null)
        } else {
            // 显示密码
            etPassword.inputType = EditorInfo.TYPE_CLASS_TEXT or
                    EditorInfo.TYPE_TEXT_VARIATION_VISIBLE_PASSWORD
            val icShow = AppCompatResources.getDrawable(baseContext, R.drawable.ic_pwd_show_20dp)
            etPassword.setCompoundDrawablesWithIntrinsicBounds(null, null, icShow, null)
        }
        isPasswordVisible = !isPasswordVisible

        // 将光标移动到文本末尾
        etPassword.setSelection(etPassword.text.length)
    }

    private fun setRemoteListener() {
        cbRemote.setOnCheckedChangeListener { buttonView, isChecked ->
            if (isChecked) {
                protocolSection.visibility = LinearLayout.VISIBLE
            } else {
                protocolSection.visibility = LinearLayout.INVISIBLE
            }
            // 清除密码框的焦点
            etPassword.clearFocus()
            // 隐藏软键盘
            hideKeyboard(etPassword)
            // 校验登录表单
            validLoginForm()
        }
    }

    private fun hideKeyboard(view: View) {
        val imm = getSystemService(INPUT_METHOD_SERVICE) as InputMethodManager
        imm.hideSoftInputFromWindow(view.windowToken, 0)
    }

    private fun setRemoteDescListener() {
        ibRemoteDesc.setOnClickListener {
            tvRemote.performLongClick()
        }
    }

    private fun setAgreeProtocolListener() {
        rbAgreeProtocol.setOnClickListener {
            // 点击同意协议时校验登录表单
            validLoginForm()
        }
    }

    private fun validLoginForm() {
        val account = etAccount.text.toString()
        val password = etPassword.text.toString()
        val etValid = account.isNotEmpty() && password.length >= 6
        loginEnable = etValid && (!cbRemote.isChecked || cbRemote.isChecked && rbAgreeProtocol.isChecked)
        if (loginEnable) {
            btLogin.setBackgroundResource(R.drawable.login_button_enable_style)
        } else {
            btLogin.setBackgroundResource(R.drawable.login_button_disable_style)
        }
    }

    private fun setLoginListener() {
        btLogin.setOnClickListener {
            // 处理登录逻辑
            if(validate()){
                // 跳转到MainActivity
                val intent = Intent(baseContext, MainActivity::class.java)
                //intent.putExtra("username", account) // 传递用户名参数
                startActivity(intent)
                finish()
            }
        }
    }

    private fun validate(): Boolean {
        val account = etAccount.text.toString()
        if(account.isEmpty()) {
            etAccount.error = "账号不能为空"
            return false
        }
        val password = etPassword.text.toString()
        if(password.length < 6) {
            etPassword.error = "密码至少6位"
            return false
        }
        if (!loginEnable) {
            Toast.makeText(baseContext, "请先阅读协议，并确认勾选", Toast.LENGTH_SHORT).show()
            return false
        }
        return "admin" == account && "123456" == password
    }

    private fun setOtherLoginListener() {
        tvOtherLogin.setOnClickListener {
            // 跳转到MainActivity
            val intent = Intent(this, LoginGestureActivity::class.java)
            startActivity(intent)
            finish()
        }
    }
}
